﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Sinacor.Infra.Service.Data;
using System.ComponentModel;
using Sinacor.Infra.Common;

namespace Sinacor.Infra.Service.Data
{
    public static class IDataReaderExtesionMethods
    {
        /// <summary>
        /// Captura o valor de uma coluna
        /// </summary>
        /// <typeparam name="T">Type do valor a ser capturado</typeparam>
        /// <param name="reader">IDataReader com a coluna</param>
        /// <param name="columnName">Nome da coluna</param>
        /// <returns>Valor da coluna</returns>
        public static T GetValue<T>(this IDataReader reader, string columnName)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");
            if (columnName == null)
                throw new ArgumentNullException("columnName");

            int index = reader.GetOrdinal(columnName);
            if (index < 0)
                throw new ArgumentOutOfRangeException("columnName", columnName, "Invalid column name");
            else
            {
                object value;
                value = reader.GetValue(index);

                if (value == null || value == DBNull.Value)
                {
                    //se o retorno aceitar nulo, ou for do tipo string
                    if (typeof(T).IsNullable() || typeof(T) == typeof(string))
                    {
                        value = null;
                        return (T)value;
                    }
                    else
                        throw new InvalidCastException(string.Format("The value of column '{0}' is null but the type '{1}' doesn't allow null", columnName, typeof(T).Name));
                }
                else
                {
                    if (typeof(T).IsNullable())
                    {
                        Type t = new NullableConverter(typeof(T)).UnderlyingType;
                        value = Convert.ChangeType(value, t);
                        return (T)value;
                    }
                    else
                    {
                        //removido por apresentar problemas com tipos 'nullable'
                        value = Convert.ChangeType(value, typeof(T));
                        return (T)value;
                    }
                }
            }
        }
    }
}
